package com.gccloud.design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gccloud.design.dao.SdOptBranchDao;
import com.gccloud.design.dto.SdOptBranchDto;
import com.gccloud.design.entity.SdOptBranchEntity;
import com.gccloud.design.feign.BwpOperDockingClient;
import com.gccloud.design.service.SdOptBranchService;
import com.gccloud.idc.security.shiro.UserUtils;
import com.gccloud.starter.common.exception.GlobalException;
import com.gccloud.starter.common.vo.R;
import com.gccloud.starter.core.vo.PageVO;
import com.gccloud.starter.mybatis.utils.QueryWrapperUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author wu.yumin
 * @version 1.0.0
 * @Description 流程操作分支配置
 * @date 2021/7/19 10:19
 */
@Service
@Slf4j
public class SdOptBranchServiceImpl extends ServiceImpl<SdOptBranchDao, SdOptBranchEntity> implements SdOptBranchService {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();


    @Resource
    BwpOperDockingClient bwpOperDockingClient;

    @Override
    public boolean addOptBranch(SdOptBranchEntity entity) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("action",entity.getTriggerFunction());
        paramMap.put("businessTypeId",entity.getBusinessTypeId());
        paramMap.put("code",entity.getBranchCode());
        paramMap.put("displayName",entity.getBranchShowName());
        paramMap.put("memo",entity.getComments());
        paramMap.put("name",entity.getTriggerFunction());
        R result = bwpOperDockingClient.saveOptBtnBranch(gson.toJson(paramMap));
        if (result.getCode()!=200){
            log.info("创建流程操作失败");
            throw new GlobalException("创建流程操作失败",500);
        }
        entity.setBranchId(Long.parseLong(result.getData().toString()));
        try {

            entity.setCreateUserId(UserUtils.getCurrentUserId());
            entity.setCreateUserName(UserUtils.getCurrentUserName());
            entity.setShardingId(0);
            return saveOrUpdate(entity);
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    @Override
    public boolean updateOptBranch(SdOptBranchEntity entity) {
        if(entity.getBranchId() == null || entity.getBranchId() == 0 ){
            throw new IllegalArgumentException("记录不存在");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("action",entity.getTriggerFunction());
        paramMap.put("id",entity.getBranchId());
        paramMap.put("code",entity.getBranchCode());
        paramMap.put("displayName",entity.getBranchShowName());
        paramMap.put("memo",entity.getComments());
        paramMap.put("name",entity.getTriggerFunction());
        R result = bwpOperDockingClient.updateOptBtnBranch(gson.toJson(paramMap));
        if (result.getCode()!=200){
            log.info("修改流程操作失败");
            throw new GlobalException("修改流程操作失败",500);
        }
        UpdateWrapper<SdOptBranchEntity> updateWrapper = new UpdateWrapper();
        try {
            updateWrapper.set("BRANCH_CODE",entity.getBranchCode())
                    .set("BRANCH_NAME",entity.getBranchName())
                    .set("BRANCH_SHOW_NAME",entity.getBranchShowName())
                    .set("TRIGGER_FUNCTION",entity.getTriggerFunction())
                    .set("COMMENTS",entity.getComments())
                    .set("LAST_MOD_USER_ID",UserUtils.getCurrentUserId())
                    .set("LAST_MOD_TIME",sdf.format(new Date()))
                    .eq("BRANCH_ID",entity.getBranchId());
            return update(updateWrapper);
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    @Override
    public boolean deleteOptBranch(Long[] ids) {
        if(ids == null || ids.length < 1 ){
            throw new IllegalArgumentException("记录不存在");
        }
        R result = bwpOperDockingClient.deleteOptBtnBranch(org.apache.commons.lang.StringUtils.join(ids,"-"));
        if (result.getCode()!=200){
            log.info("删除流程操作失败");
            throw new GlobalException("删除流程操作失败",500);
        }
        UpdateWrapper<SdOptBranchEntity> updateWrapper = new UpdateWrapper();
        updateWrapper.set("DEL_FLAG",1).in("BRANCH_ID",ids);
        try {
            return update(updateWrapper);
        }catch (Exception e){
            log.error(ExceptionUtils.getStackTrace(e));
            return false;
        }
    }

    @Override
    public PageVO<SdOptBranchEntity> queryPageList(SdOptBranchDto searchDTO) {
        LambdaQueryWrapper<SdOptBranchEntity> queryWrapper = QueryWrapperUtils.wrapperLike(
                new LambdaQueryWrapper<>(),searchDTO.getSearchKey(),SdOptBranchEntity::getBranchCode,SdOptBranchEntity::getBranchName)
                .eq(SdOptBranchEntity::getDelFlag,0).eq(SdOptBranchEntity::getBusinessTypeId,searchDTO.getBusinessTypeId()).orderByDesc(SdOptBranchEntity::getCreateTime);
        Page<SdOptBranchEntity> searchPage = new Page<>(searchDTO.getCurrent(),searchDTO.getSize());
        Page<SdOptBranchEntity> page = page(searchPage,queryWrapper);
        return new PageVO<>(page);
    }

    @Override
    public SdOptBranchEntity getByCode(String branchCode) {
        QueryWrapper<SdOptBranchEntity> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isEmpty(branchCode)){
            throw new IllegalArgumentException("记录不存在");
        }
        queryWrapper.eq("BRANCH_CODE",branchCode);
        SdOptBranchEntity entity = getOne(queryWrapper);
        return entity;
    }

}
